<template>
  <PageContainer>
    <PaymentOnlineModal key="1" @onSuccess="onSuccess" v-model="paymentOnlineVisible" :businessTypeOptions="businessTypeOptions" />
    <ImportBulkPayment key="2" @onSuccess="onSuccess" v-model="importBulkPaymentVisible" :businessTypeOptions="businessTypeOptions" />
    <SettleModal v-model="settleModalVisible" :selectedRow="selectedRow" @onSuccess="onSettleSuccess" />
    <el-tabs type="border-card">
      <el-tab-pane label="派单项目打款">
        <el-steps align-center>
          <el-step title="打款批次提交" />
          <el-step title="服务商接单审核" />
          <el-step title="打款完成" />
        </el-steps>
        <div class="tips" style="margin-top: 10px;">
          温馨提示:
          <div style="margin-top: 5px;">1.批量打款模版使用说明：单批次最大支持500条订单，文件格式为Excel，示例：YYYYMMDD-两位编号，编号不可重复。例如：20230520-01。</div>
          <div style="margin-top: 5px;">2.批次打款限额每人单笔最高10万元，每年120万元以内，超出限额订单将会打款失败。</div>
        </div>
        <div class="content-center" style="padding: 30px;">
          <el-space>
            <el-button type="primary" @click="paymentOnlineVisible = true;onClose();">在线打款</el-button>
            <el-button @click="download">下载批量打款模板.XLS</el-button>
            <el-button type="primary" @click="importBulkPaymentVisible = true;onClose();">上传批量打款文件</el-button>
            <el-button type="danger" v-if="payError" @click="importExcel">下载批量打款失败Excel文件</el-button>
          </el-space>
        </div>
        <import-results @onClose="onClose" @onSubmit="onAddBill" :keyId="importResultId" :success="uploadResult.success" :allRecords="uploadResult.allRecords" :list="uploadResult.list" :imported="uploadResult.imported" />
      </el-tab-pane>
      <el-tab-pane label="抢单项目打款">
        <dynamic-form :items="items" v-model="formData" @onFinish="submit" />
        <ElTableWithColumns
          :loading="loading"
          :data="tableData"
          :columns="columns"
          :pagerInfo="pagerInfo"
          :operateColProps="{ width: 120, fixed: false }"
        >
          >
          <template #operate="{row}">
            <div>
              <el-tag type="success" @click="openSettleModal(row)"  style="cursor: pointer;">服务费结算</el-tag>
            </div>
          </template>
        </ElTableWithColumns>
      </el-tab-pane>
    </el-tabs>
  </PageContainer>
</template>

<script lang="ts" setup>
import DynamicForm from '@/components/DynamicForm/index.vue';
import PaymentOnlineModal from './common/PaymentOnlineModal.vue'
import SettleModal from './common/SettleModal.vue'
import ImportBulkPayment from './common/ImportBulkPayment.vue'
import ImportResults from  './common/ImportResults.vue'
import {selBtByMs,addBill} from "@/api/settlementManagement/settlementPayment/index"
import useDictUtilsStore from '@/store/modules/dict_utils'
import { TaskInfo } from '@/views/project/types'
import useUserStore from '@/store/modules/user'
import fs from 'file-saver'
import * as XLXS from "xlsx"

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { wxfe_bus_type } = toRefs<any>(proxy?.useDict("wxfe_bus_type"));
const { task_type } = toRefs<any>(proxy?.useDict("task_type"));


const { getlabel } = useDictUtilsStore()

const settleModalVisible = ref(false)
const paymentOnlineVisible = ref(false)
const importBulkPaymentVisible = ref(false)
const importResultId = ref('importResultId')
const uploadResult = reactive({
  success: false,
  list: [],
  params:{},
  allRecords:0,
  imported: false
})


const pagerInfo = reactive({
  pageSize: 10,
  total: 0,
  pageNum: 1
})


const loading = ref(false)
const payError = ref(false);
const tableData = ref([])
const selectedRow = ref({})

const openSettleModal = row => {
  settleModalVisible.value = true
  selectedRow.value = row
}




const onClose = () => {

  uploadResult.success = false
  uploadResult.imported = false
  uploadResult.list = []
  uploadResult.params = {};
  uploadResult.allRecords = 0 ;
  payError.value = false;
}

const onSuccess = (payload) => {

  const { success, data: { list, errorList = [] },allRecords,params } = payload
  if(!success){
    payError.value = true;
  }else{
    payError.value = false;
  }

  uploadResult.success = success
  uploadResult.imported = true
  uploadResult.list = list
  if(list.length > 0){
    if(list[0].billNo){
      params.no = list[0].billNo;
    }
  }
  uploadResult.params = params;
  uploadResult.allRecords = allRecords;
  paymentOnlineVisible.value = importBulkPaymentVisible.value = false
}

const download = () => {
  proxy?.download("/resource/oss/download/101", {
  }, `打款导入模板.xlsx`);
}

const onAddBill =()=>{
  proxy?.$modal.loading("正在提交数据，请稍候...");
    addBill({
        ...uploadResult.params,
        details:uploadResult.list
    }).then((res)=>{
        onClose();
        proxy?.$modal.msgSuccess("提交成功");
    }).finally(()=>{
        proxy?.$modal.closeLoading();
    });
}

const query = async (formData = {}) => {
  let defaultProvider = useUserStore().defaultProvider;
  loading.value = true
  const { response } = await useRequest('/payment/bill/balanceTaskList', 'GET', {
  params: { ...formData, sydId: defaultProvider.sydId }
}, { immediate: true })
  loading.value = false
  if (response.value?.code === 200) {
    tableData.value = response.value.rows
  }
}

const businessTypeOptions = ref([]);
const getBusType = async()=>{
    let defaultProvider = useUserStore().defaultProvider;
    selBtByMs({
      merId:defaultProvider.merId,
      sydId:defaultProvider.sydId
    }).then((res)=>{
      if(res.code == 200){
          let busTypes = res.data;
          let busArray = [] ;
         busArray =  busTypes.map(item =>{
            return {
              label:item.dictLabel,
              value:parseInt(item.dictValue)
            }
          });
          businessTypeOptions.value = busArray;
          console.log(businessTypeOptions.value)
      }
    })
}



const importExcel = ()=>{
  proxy?.$modal.loading("正在下载文件，请稍候...");
  var wb = XLXS.utils.table_to_book(document.querySelector("#importResultId"), {
    raw: true
  });
  var wbout = XLXS.write(wb, {
    bookType: "xlsx",
    bookSST: true,
    type: "array"
  });
  try {
  fs.saveAs(
    new Blob([wbout], {
      type: "application/octet-stream"
    }),
  `批量打款失败信息.xlsx`
  );
  proxy?.$modal.closeLoading();
  } catch (e) {
    console.log(e);
    proxy?.$modal.closeLoading();
  }
  return wbout;

}

onMounted(() => {
  query();
  getBusType();
})

const onSettleSuccess =()=>{
  query();
}

const columns = [
  {
    title: '创建时间',
    width:150,
    dataIndex: 'addTime',
  },
  {
    title: '项目名称',
    dataIndex: 'name',
  },
  {
    title: '项目编号',
    dataIndex: 'no',
    width:120,
  },
  {
    title: '所属行业',
    width:180,
    dataIndex: 'industryName',
    renderText: (row: any) => {
      const {industryName} = row
      // return `${row.cost} ${costMax &&( costMax !== 0) ? '~' : ''} ${row.costMax ?? ''}`
      let idns = industryName.split(",");
      if(idns.length <= 1){
        return idns[0]
      }else{
        return idns[1]
      }
    },
  },
  {
    title: '个税',
    dataIndex: 'raise',
    width:120,
  },
  {
    title: '服务金额（元）',
    dataIndex: 'taskCode',
    width:120,
    renderText: (row: TaskInfo) => {
      const {costMax} = row
      // return `${row.cost} ${costMax &&( costMax !== 0) ? '~' : ''} ${row.costMax ?? ''}`
      return proxy?.convertFenToYuan(row.cost);
    },
  },
  {
    title: '接单类型',
    dataIndex: 'classify',
    width:80,
    renderText: row => {
         return getlabel('task_type', row.classify)
    }
  },
  {
    title: '业务类型',
    width:80,
    dataIndex: 'busType',
    renderText: row => {
         return getlabel('wxfe_bus_type', row.busType)
    }
  },
]

const formData = ref({})
const submit = () => {
  const submitData = {
    ...formData.value,
    sydId: 1
  }
  query(submitData)

}

/**
 * 业务类型
*/
// const businessTypeOptions = computed(() => {
//   const list = proxy?.useDict("wxfe_bus_type").wxfe_bus_type
//   return list
// })

const items = computed(() => {
  return [
    { prop: 'addTime', label: '创建时间', valueType: 'date', fieldProps: { type: 'daterange', valueFormat: 'YYYY-MM-DD' } },
    { prop: 'no', label: '项目编号', valueType: 'input' },
    { prop: 'busType', label: '业务类型', valueType: 'select', options: businessTypeOptions.value },
  ]
})
</script>

<style>
.tips {
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    padding: 15px;
    font-size: 14px;
    border-radius: 5px;
}
.content-center {
  text-align: center;
}
</style>
